#include "SketchWidget.h"

SketchWidget::SketchWidget(const QString &tag,QWidget *parent) : QWidget(parent)
{
    TAG = tag;

    init();
}

SketchWidget::~SketchWidget()
{
    if(image)
        delete image;
    image = nullptr;

    if(buttonDelete)
        delete buttonDelete;
    buttonDelete = nullptr;

    if(label)
        delete label;
    label = nullptr;
}

void SketchWidget::init()
{
    image = new QImage;    
    label = new ShowImageLabel(this);
    buttonDelete = new QPushButton(this);
    buttonDelete->resize(28,28);
    buttonDelete->setStyleSheet("border-image: url(:/List/Resource/close.png);");
    connect(label,&ShowImageLabel::LeftButtonPress,[&](){emit OpenShow(TAG);});
    connect(buttonDelete,&QAbstractButton::pressed,[&](){emit DeleteDown(TAG);});

    setMaximumSize(WidgetSize);
    setMinimumSize(WidgetSize);
    setStyleSheet("background-color:white;");
}

bool SketchWidget::setTagImagePath(const QString &tip)
{
    bool flag = false;
    if(!tip.isEmpty() && QFile::exists(tip))
    {
        QFile fp(tip);
        if(fp.open(QFile::ReadOnly))
        {
            QByteArray data = fp.readAll();
            for(int byteArrayIndex=0;byteArrayIndex<data.size();data[byteArrayIndex] = data[byteArrayIndex] ^ 66,++byteArrayIndex);
            *image = QImage::fromData(data);
            if(!image->isNull())
            {
                ZoomImageCurWidget(image);
                label->setPixmap(QPixmap::fromImage(*image));
                flag = true;
            }
            fp.close();
        }
    }
    else
        TAG.clear();
    return flag;
}

void SketchWidget::ZoomImageCurWidget(QImage *_image)
{
    if(!_image->isNull())
        *_image = _image->scaled(WidgetSize);
}
